﻿using Microsoft.Win32;
using System;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Converter
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 打开图片的弹窗标题
        /// </summary>
        private const string title = "选择要转换的图片";
        /// <summary>
        /// 图片的文件类型
        /// </summary>
        private const string filter = "图像文件|*.jpg;*.png;*.jpeg;*.bmp;*.gif|所有文件|*.*";
        /// <summary>
        /// base64
        /// </summary>
        private const string defult = "RGV2ZWxvcGVkIGJ5IEppZSBaaGFuZw==";

        public MainWindow()
        {
            InitializeComponent();
            base64Value.Text = defult;
            imageTips.Visibility = Visibility.Collapsed;
        }

        private void Button_Convert_to_Base64_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(unbase64Value.Text)) // 判断非Base64字符串文本框中是否有文字
                {
                    base64Value.Text = String2Base64(unbase64Value.Text.ToString()).ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Convert_to_unBase64_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                unbase64Value.Text = Convert2UnBase64(base64Value.Text.ToString()).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Convert_Image_to_Base64_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                imageTips.Visibility = Visibility.Collapsed;
                string ImageBase64 = base64Value.Text;

                Image1.Source = FromBase64ToImage(ImageBase64);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Select_Image(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openfiledialog = new OpenFileDialog
                {
                    Title = title,
                    Filter = filter
                };

                if ((bool)openfiledialog.ShowDialog())
                {
                    Image1.Source = new BitmapImage(new Uri(openfiledialog.FileName));
                    imageShow.Visibility = Visibility.Collapsed;
                    unbase64Value.Clear();
                    base64Value.Clear();
                    imageTips.Visibility = Visibility.Visible;
                    base64Value.Text = FromImageToBase64(openfiledialog.FileNames[0].ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Image_Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveFileDialog SaveImg = new SaveFileDialog
                {
                    Filter = filter,
                    RestoreDirectory = true // 记录上次打开的路径历史
                };
                if (SaveImg.ShowDialog() == true)
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create((BitmapSource)Image1.Source));
                    using (FileStream stream = new FileStream(SaveImg.FileName, FileMode.Create))
                        encoder.Save(stream);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        
        private void Button_Hex2String_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StringValue.Text = Hex2String(HexValue.Text.ToString()).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_String2Hex_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                HexValue.Text = String2hexbyte(StringValue.Text.ToString()).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Rot13ToString_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StringValue_2.Text = Rot13ToString(rotValue.Text.ToString()).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        
        //private void Button_BinaryEncoder_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        BinaryValue.Text = BinaryEncode(DecodeBinaryValue.Text.ToString()).ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        //private void Button_BinaryDecoder_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        DecodeBinaryValue.Text = BinaryDecode(BinaryValue.Text.ToString()).ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        #region 清空编辑框按钮
        private void Button_Clean_Click(object sender, RoutedEventArgs e)
        {
            base64Value.Text = "";
            unbase64Value.Text = "";
        }

        private void Button_Clean_2_Click(object sender, RoutedEventArgs e)
        {
            HexValue.Text = "";
            StringValue.Text = "";
        }

        private void Button_Clean_3_Click(object sender, RoutedEventArgs e)
        {
            rotValue.Text = "";
            StringValue_2.Text = "";
        }

        //private void Button_Clean_4_Click(object sender, RoutedEventArgs e)
        //{
        //    DecodeBinaryValue.Text = "";
        //    BinaryValue.Text = "";
        //}
        #endregion

        /// <summary>
        /// string转换为base64字符串
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        private string String2Base64(string a)
        {
            imageTips.Visibility = Visibility.Collapsed;
            string afterConvert = string.Empty;
            byte[] b = Encoding.UTF8.GetBytes(a);
            afterConvert = Convert.ToBase64String(b); // UTF8为了避免中文乱码的情况

            return afterConvert;
        }

        /// <summary>
        /// base64字符串转换为string
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private string Convert2UnBase64(string b)
        {
            string afterConvert = string.Empty;
            byte[] a = Convert.FromBase64String(b);
            afterConvert = Encoding.UTF8.GetString(a);

            return afterConvert;
        }

        /// <summary>
        /// Base64字符串转换为图片
        /// </summary>
        /// <param name="ImageBase64">图片的Base64字符串</param>
        /// <returns></returns>
        private BitmapImage FromBase64ToImage(string ImageBase64)
        {
            BitmapImage bitmapImage = new BitmapImage();

            var bytes = Convert.FromBase64String(ImageBase64);
            BitmapImage bmp = null;

            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(bytes);
                bmp.EndInit();
                bitmapImage = bmp;
                imageShow.Visibility = Visibility.Collapsed;

                return bitmapImage;
            }
            catch (Exception ex)
            {
                MessageBox.Show("此Base64字符串不是图片，请选择上方其他的转换按钮 | 错误信息：" + ex.Message);
                imageShow.Visibility = Visibility.Visible;
                return new BitmapImage();
            }
        }

        /// <summary>
        /// 图片转换为Base64字符串
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private string FromImageToBase64(string filePath)
        {
            string returnBase64Value = string.Empty;
            byte[] bytes = null;
            try
            {
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return string.Empty;
            }

            returnBase64Value = Convert.ToBase64String(bytes);

            return returnBase64Value;
        }

        /// <summary>
        /// string转换为16进制
        /// </summary>
        /// <param name="stringValue"></param>
        /// <returns></returns>
        private string String2hexbyte(string stringValue)
        {
            return BitConverter.ToString(Encoding.Default.GetBytes(stringValue)).Replace("-", "");
        }

        /// <summary>
        /// 16进制转换为string
        /// </summary>
        /// <param name="HexValue"></param>
        /// <returns></returns>
        private string Hex2String(string HexValue)
        {
            HexValue = HexValue.Replace(" ", "");
            if (HexValue.Length <= 0) return "";
            byte[] vBytes = new byte[HexValue.Length / 2];
            for (int i = 0; i < HexValue.Length; i += 2)
                if (!byte.TryParse(HexValue.Substring(i, 2), NumberStyles.HexNumber, null, out vBytes[i / 2]))
                    vBytes[i / 2] = 0;
            return Encoding.Default.GetString(vBytes);
        }

        /// <summary>
        /// rot13编解码（rot13是个单纯的字符替换，是一个可逆过程，因此不需要再写一个方法）
        /// </summary>
        /// <param name="rot13Value"></param>
        /// <returns></returns>
        private string Rot13ToString(string rot13Value)
        {
            int i;
            char CurrentCharacter;
            int CurrentCharacterCode;
            string EncodedText = "";

            //Iterate through the length of the input parameter  
            for (i = 0; i < rot13Value.Length; i++)
            {
                //Convert the current character to a char  
                CurrentCharacter = Convert.ToChar(rot13Value.Substring(i, 1));

                //Get the character code of the current character  
                CurrentCharacterCode = (int)CurrentCharacter;
                //Modify the character code of the character, - this  
                //so that "a" becomes "n", "z" becomes "m", "N" becomes "Y" and so on  
                if (CurrentCharacterCode >= 97 && CurrentCharacterCode <= 109)
                {
                    CurrentCharacterCode = CurrentCharacterCode + 13;
                }
                else if (CurrentCharacterCode >= 110 && CurrentCharacterCode <= 122)
                {
                    CurrentCharacterCode = CurrentCharacterCode - 13;
                }
                else if (CurrentCharacterCode >= 65 && CurrentCharacterCode <= 77)
                {
                    CurrentCharacterCode = CurrentCharacterCode + 13;
                }
                else if (CurrentCharacterCode >= 78 && CurrentCharacterCode <= 90)
                {
                    CurrentCharacterCode = CurrentCharacterCode - 13;
                }

                //Add the current character to the string to be returned  
                EncodedText = EncodedText + (char)CurrentCharacterCode;
            }

            return EncodedText;
        }

        /// <summary>
        /// 将字符串转成二进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string BinaryEncode(string s)
        {
            byte[] data = Encoding.Unicode.GetBytes(s);
            StringBuilder result = new StringBuilder(data.Length * 8);

            foreach (byte b in data)
            {
                result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
            }
            return result.ToString();
        }
        
        /// <summary>
        /// 将二进制转成字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string BinaryDecode(string s)
        {
            System.Text.RegularExpressions.CaptureCollection cs =
                System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures;
            byte[] data = new byte[cs.Count];
            for (int i = 0; i < cs.Count; i++)
            {
                data[i] = Convert.ToByte(cs[i].Value, 2);
            }
            return Encoding.Unicode.GetString(data, 0, data.Length);
        }
        
    }
}
